<template>
  <div class="app-content flex-column">
    <el-form :model="queryParams" ref="queryRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item prop="controllerListName">
            <el-input v-model="queryParams.controllerListName" placeholder="网关名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="ruleCategory">
            <el-select v-model="queryParams.ruleCategory" clearable placeholder="规则类别">
              <el-option v-for="(item,index) in ruleList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="ruleType">
            <el-select v-model="queryParams.ruleType" clearable placeholder="状态">
              <el-option label="预警" :value="1"></el-option>
              <el-option label="告警" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <RichTable class="flex1" ref="richTableRef" height="0" :page="params" :options="options">
      <template #ruleCategory="{ row }">
        <div>
          <span v-if="row.ruleCategory=='1'">天气</span>
          <span v-else-if="row.ruleCategory=='2'">温度</span>
          <span v-else-if="row.ruleCategory=='3'">电压</span>
          <span v-else-if="row.ruleCategory=='4'">电流</span>
          <span v-else-if="row.ruleCategory=='5'">功率</span>
        </div>
      </template>
    </RichTable>

    <el-drawer :title="`${dialogType=='add'?'新增':'编辑'}预警配置`" v-model="drawerVisible" size="750" append-to-body>
      <el-form label-width="110px" ref="formRef" :model="form" :rules="rules">
        <el-form-item label="规则网关" prop="controllerList">
          <el-cascader style="width: 100%;" v-model="form.controllerList" placeholder="请选择规则网关" :options="controllerList" clearable :props="{
              children: 'controllerList',
              label: 'name',
              multiple:true,
              emitPath: false, // 关键设置：只返回最后一级节点的值
            }" :show-all-levels="false" />
        </el-form-item>
        <el-form-item label="规则编码" prop="ruleCode">
          <el-input placeholder="请输入规则编码" v-model="form.ruleCode"></el-input>
        </el-form-item>
        <el-form-item label="规则类别" prop="ruleCategory">
          <el-select style="width: 100%;" v-model="form.ruleCategory" placeholder="请选择规则类别" @change="handleChangeRuleCategory">
            <el-option v-for="(item,index) in ruleList" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则类型" prop="ruleType">
          <el-select style="width: 100%;" v-model="form.ruleType" placeholder="请选择规则类型">
            <el-option label="预警" :value="1"></el-option>
            <el-option label="告警" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="规则" prop="rule">
          <div style="display: flex;flex-wrap: wrap;align-items: flex-start;">
            <span v-if="ruleLabel" class="mr10">{{ ruleLabel }}</span>
            <el-select v-if="form.ruleCategory!=1" class="mr10" style="width: 100px;" v-model="form.compareType" placeholder="请选择">
              <el-option label="同比" :value="1"></el-option>
              <el-option label="上一条" :value="2"></el-option>
            </el-select>
            <el-select v-if="form.ruleCategory!=1" class="mr10" style="width: 100px;" v-model="form.compareDirection" placeholder="请选择">
              <el-option label="增加" :value="1"></el-option>
              <el-option label="减少" :value="2"></el-option>
            </el-select>
            <el-select class="mr10" style="width: 100px;margin-bottom: 10px;" v-model="form.compareSymbol" placeholder="请选择">
              <el-option label=">=" value=">="></el-option>
              <el-option label="<=" value="<="></el-option>
              <el-option label="∈" value="∈"></el-option>
            </el-select>
            <!-- <el-input-number class="mr10" style="width: 100px;" controls-position="right" placeholder="请输入" v-model="form.compareResultValue" /> -->
            <el-input :style="{width: (form.ruleCategory&&form.ruleCategory!=1)?'220px':'260px'}" placeholder="请输入" v-model="form.compareResultValue"></el-input>
            <el-select v-if="form.ruleCategory!=1" style="width: 100px;" v-model="form.compareResultValueUnit" placeholder="请选择">
              <el-option label="%" value="%"></el-option>
              <el-option label="无" value=""></el-option>
            </el-select>
          </div>
        </el-form-item>

        <el-form-item label="关联操作">
          <el-checkbox :disabled="[1].includes(form.ruleCategory)" label="自动关闭" v-model="form.autoClose" :false-value="0" :true-value="1" />
          <el-checkbox label="自动创建工单" v-model="form.autoOrder" :false-value="0" :true-value="1" />
          <el-checkbox label="是否短信通知" v-model="form.autoSms" :false-value="0" :true-value="1" />
        </el-form-item>

        <el-form-item label="规则提示语">
          <!-- 当前电压30w,同比下降5% -->
          <!-- 当前$ruleCategory 30w,$ruleCategory1 同比下降5% -->
          <el-input placeholder="请输入规则提示语" type="textarea" :rows="4" v-model="form.ruleDescribe"></el-input>
        </el-form-item>
        <el-form-item label="提示语占位符:">
          <div>
            <div>数据源-$source</div>
            <div>比较值-$target</div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancle">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { deviceTreeListApi,ruleConfigApi,delRuleConfigApi } from '@/api/station';
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
import { ElMessageBox, ElNotification } from "element-plus";
import { Close } from '@element-plus/icons-vue'

// 列表
const richTableRef = ref();
const params = ref({
  page: 1,
  size: 30,
  total:0
})

const options = ref({
  header:false,
  // 表格接口
  tableRequest: {
    url: '/bopeng-cms/ruleConfig/list',
    method: 'get',
    params: {
      stationId:userStore.stationInfo.stationId,
      source:2, // 1：系统 2：网关
      controllerListName:'',
      ruleCategory:'',
      ruleType:''
    }
  },
  // 表格操作
  tableEvent: [
    {
      label: "新增",
      title: '新增电站',
      callback: () => {
        form.value = {
          source:2,
          stationId:userStore.stationInfo.stationId,
          controllerList:[],
          ruleCode:'',
          ruleCategory: '',
          ruleType: '',
          compareType: '',
          compareSymbol: '',
          compareResultValue: '',
          compareResultValueUnit: '',
          autoClose:0,
          autoOrder:0,
          autoSms:0,
          ruleDescribe: '',
        }
        dialogType.value = 'add'
        drawerVisible.value = true
      }
    }
  ],
  column: [
    { prop: 'controllerListName', label: '网关名称', attrs: { showOverflowTooltip: true } },
    { prop: 'ruleCode', label: '规则编码', attrs: { showOverflowTooltip: true } },
    { prop: 'ruleCategory', label: '规则类别', attrs: { width: 160, showOverflowTooltip: true } },
    { prop: 'ruleType', label: '规则类型', attrs: { showOverflowTooltip: true },formatter: (row) => {
        if(row.ruleType==1) {
          return '预警'
        }else if(row.ruleType==2) {
          return '告警'
        }
    }, },
    { prop: 'ruleDescribe', label: '规则提示语', attrs: { showOverflowTooltip: true } },
    { prop: 'createTime', label: '创建时间', attrs: { width: 160, showOverflowTooltip: true } },
    { prop: 'updateTime', label: '更新时间', attrs: { width: 160, showOverflowTooltip: true } },
    { type: 'operation', width:150 },
  ],
  rowEvent: [
    {
      label: "编辑",
      callback: (row) => {
        dialogType.value = 'edit'
        drawerVisible.value = true
        let obj = {...row}
        if(obj.controllerList) {
          obj.controllerList = obj.controllerList.split(';')
        }
        form.value = obj;
      }
    },2
    {
      label: '删除',
      callback: (row) => {
        ElMessageBox.confirm(`你确定要删除该预警配置吗？`, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
          autofocus: false,
          closeOnClickModal: false,
        }).then(() => {
            const params = [row.id];
            delRuleConfigApi(params).then((res) => {
              if (res) {
                ElNotification({
                  title: "成功",
                  message: "删除成功",
                  type: "success",
                });
                handleQuery();
              }
            }).catch((err) => {});
        }).catch(() => {})
      }
    },
  ]
})
const queryParams = toRefs(options.value.tableRequest).params // 保持响应式的解构

/** 搜索按钮操作 */
const handleQuery = () => {
  richTableRef.value.initTable()
}
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef")
  richTableRef.value.initTable()
}

/** 新增/编辑 */
const drawerVisible = ref(false)
const dialogType = ref('add') // add 新增 edit 编辑
// 当前的表单的实例
const formRef = ref()
const form = ref({
  // source:2,
  // stationId:userStore.stationInfo.stationId,
  // controllerList:[],
  // ruleCategory: '',
  // ruleType: '',
  // compareType: '',
  // compareSymbol: '',
  // compareResultValue: 0,
  // compareResultValueUnit: '',
  // autoClose:0,
  // autoOrder:0,
  // ruleDescribe: '',
})
// 表单校验规则
const rules = reactive({
  controllerList: [
    { required: false, message: "规则网关不能为空", trigger: ["blur"], },
  ],
  ruleCode: [
    { required: true, message: "规则编码不能为空", trigger: ["blur"], },
  ],
  ruleCategory: [
    { required: true, message: "规则类别不能为空", trigger: ["blur"], },
  ],
  ruleType: [
    { required: true, message: "规则类型不能为空", trigger: ["blur"], },
  ],
  rule: [
    { required: true,validator: (rule, value, callback) => {
      if(form.value.ruleCategory==1 && (!form.value.compareSymbol || !form.value.compareResultValue)) {
        return callback(new Error('规则不能为空'));
      }
      if(form.value.ruleCategory!=1 && (!form.value.compareType || !form.value.compareDirection || !form.value.compareSymbol || !form.value.compareResultValue)) {
        return callback(new Error('规则不能为空'));
      }
      callback();
    }, trigger: ["blur"], }
  ],
})

const handleCancle = () => {
  drawerVisible.value = false
}

// 新增/编辑 预警规则
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res = await ruleConfigApi(dialogType.value,form.value)
        ElNotification({
          title: "成功",
          message: `${dialogType.value=='add'?'新增':'编辑'}成功！`,
          type: "success",
        });
        handleCancle()
        handleQuery()
      }catch(err) {}
    }
  })
}

// 获取电站网关树
const controllerList = ref([])
const getDeviceTreeList = async () => {
  try {
    let res = await deviceTreeListApi({
      stationId:userStore.stationInfo.stationId
    })
    controllerList.value = res.data.map(item => {
      return {
        name:item.controllerName,
        value:item.controllerNo
      }
    })
  }catch(err) {}
}
// 表单的下拉选项
const ruleList = ref([
  { label:"天气", value:1 },
  { label:"温度", value:2 },
  { label:"电压", value:3 },
  { label:"电流", value:4 },
  { label:"功率", value:5 },
])
const ruleLabel = computed(() => {
  return (ruleList.value.find(item => item.value==form.value.ruleCategory)||{}).label
})
const handleChangeRuleCategory = () => {
  form.value.compareType = ''
  form.value.compareSymbol = ''
  form.value.compareDirection = ''
  form.value.compareResultValue = ''
  form.value.compareResultValueUnit = ''
  form.value.autoClose = 0
  form.value.autoOrder = 0
  form.value.autoSms = 0
}

onMounted(() => {
  getDeviceTreeList()
})
</script>

<style lang="scss" scoped>
.app-content {
  height: calc(100vh - 84px);
}

.header {
  color: #253440;
  height: 24px;
  line-height: 24px;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 16px;
  display: flex;
  align-items: center;

  .header-title {
    flex: 1;

    span {
      padding-left: 4px;
    }
  }
}

.controller {
  .controller-header {
    background-color: #F1F5F8FF;
    height: 40px;
    box-sizing: border-box;
    line-height: 20px;
    display: flex;
    padding: 10px 14px;
    margin-bottom: 12px;

    .controller-header-text {
      flex: 1;
      font-size: 14px;
    }

    .controller-header-close {
      cursor: pointer;
      font-size: 12px;
      color: var(--el-color-primary);
    }
  }
}
</style>
